
 <!DOCTYPE HTML>
<html >
<head>
  <meta charset="UTF-8">
  
    <title>springboot(19)-security | Typhoon&#39;s code space</title>
    <meta name="viewport" content="width=device-width, initial-scale=1,user-scalable=no">
    
    <meta name="author" content="typhoon">
    

    
    <meta name="description" content="Spring Security是一种功能强大、高度可定制的身份验证和访问控制框架。这也是是保护基于Spring 的应用程序的标准。">
<meta name="keywords" content="springboot">
<meta property="og:type" content="article">
<meta property="og:title" content="springboot(19)-security">
<meta property="og:url" content="http://scorpioaeolus.oschina.io/2018/11/18/springboot-19-security/index.html">
<meta property="og:site_name" content="Typhoon&#39;s code space">
<meta property="og:description" content="Spring Security是一种功能强大、高度可定制的身份验证和访问控制框架。这也是是保护基于Spring 的应用程序的标准。">
<meta property="og:image" content="http://scorpioaeolus.oschina.io/typhoon/2018/11/18/springboot-19-security/sb1.png">
<meta property="og:image" content="http://scorpioaeolus.oschina.io/typhoon/2018/11/18/springboot-19-security/sb2.png">
<meta property="og:image" content="http://scorpioaeolus.oschina.io/typhoon/2018/11/18/springboot-19-security/sb3.png">
<meta property="og:image" content="http://scorpioaeolus.oschina.io/typhoon/2018/11/18/springboot-19-security/sb5.png">
<meta property="og:image" content="http://scorpioaeolus.oschina.io/typhoon/2018/11/18/springboot-19-security/sb4.png">
<meta property="og:updated_time" content="2018-11-18T08:02:58.979Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="springboot(19)-security">
<meta name="twitter:description" content="Spring Security是一种功能强大、高度可定制的身份验证和访问控制框架。这也是是保护基于Spring 的应用程序的标准。">
<meta name="twitter:image" content="http://scorpioaeolus.oschina.io/typhoon/2018/11/18/springboot-19-security/sb1.png">

    
    <link rel="alternative" href="/atom.xml" title="Typhoon&#39;s code space" type="application/atom+xml">
    
    
    <link rel="icon" href="/typhoon/img/java.png">
    
    
    <link rel="apple-touch-icon" href="/typhoon/img/jacman.jpg">
    <link rel="apple-touch-icon-precomposed" href="/typhoon/img/jacman.jpg">
    
    <link rel="stylesheet" href="/typhoon/css/style.css">
</head>

  <body>
    <header>
      
<div>
		
			<div id="imglogo">
				<a href="/typhoon/"><img src="/typhoon/img/java.png" alt="Typhoon&#39;s code space" title="Typhoon&#39;s code space"/></a>
			</div>
			
			<div id="textlogo">
				<h1 class="site-name"><a href="/typhoon/" title="Typhoon&#39;s code space">Typhoon&#39;s code space</a></h1>
				<h2 class="blog-motto"></h2>
			</div>
			<div class="navbar"><a class="navbutton navmobile" href="#" title="Menu">
			</a></div>
			<nav class="animated">
				<ul>
					<ul>
					 
						<li><a href="/typhoon/">主页</a></li>
					
						<li><a href="/typhoon/archives">归档</a></li>
					
						<li><a href="/typhoon/about">关于</a></li>
					
					<li>
 					
					<form class="search" action="//google.com/search" method="get" accept-charset="utf-8">
						<label>Search</label>
						<input type="search" id="search" name="q" autocomplete="off" maxlength="20" placeholder="Search" />
						<input type="hidden" name="q" value="site:scorpioaeolus.oschina.io">
					</form>
					
					</li>
				</ul>
			</nav>			
</div>
    </header>
    <div id="container">
      <div id="main" class="post" itemscope itemprop="blogPost">
  
	<article itemprop="articleBody"> 
		<header class="article-info clearfix">
  <h1 itemprop="name">
    
      <a href="/typhoon/2018/11/18/springboot-19-security/" title="springboot(19)-security" itemprop="url">springboot(19)-security</a>
  </h1>
  <p class="article-author">By
       
		<a href="/typhoon/about" title="typhoon" target="_blank" itemprop="author">typhoon</a>
		
  <p class="article-time">
    <time datetime="2018-11-18T06:44:42.000Z" itemprop="datePublished"> Published 2018-11-18</time>
    
  </p>
</header>
	<div class="article-content">
		
		<div id="toc" class="toc-article">
			<strong class="toc-title">Contents</strong>
		
			<ol class="toc"><li class="toc-item toc-level-5"><a class="toc-link" href="#目标"><span class="toc-number">1.</span> <span class="toc-text">目标</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#技术实现"><span class="toc-number">2.</span> <span class="toc-text">技术实现</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#测试"><span class="toc-number">3.</span> <span class="toc-text">测试</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#总结"><span class="toc-number">4.</span> <span class="toc-text">总结</span></a></li></ol>
		
		</div>
		
		<pre><code>    Spring Security是一种功能强大、高度可定制的身份验证和访问控制框架。这也是是保护基于Spring
的应用程序的标准。
</code></pre><a id="more"></a>
<pre><code>    Spring Security是一个专注于向Java应用程序提供身份验证和授权的框架。与所有的Spring项目一样，
Spring Security的真正功能在于它可以容易地扩展以满足定制需求。
</code></pre><p><strong>特性</strong></p>
<ul>
<li>认证和授权的全面和可扩展的支持</li>
<li>防止攻击，如会话固定、点击劫持、跨站点请求伪造等</li>
<li>Servlet API集成</li>
<li>与Spring Web MVC的可选集成</li>
<li><p>更多比如和springboot应用集成，与Auth2集成，与jwt集成等等</p>
<pre><code>本篇文章中我们将基于springboot整合spring security5。
</code></pre><h5 id="目标"><a href="#目标" class="headerlink" title="目标"></a>目标</h5><pre><code>基于springboot2.x集成spring security5，实现应用资源的保护：
</code></pre></li>
<li>用户登陆后才能访问服务端资源</li>
<li>拥有特定权限后才能访问受保护资源</li>
</ul>
<h5 id="技术实现"><a href="#技术实现" class="headerlink" title="技术实现"></a>技术实现</h5><pre><code>     介于springboot和spring security都是一家的产品，在融合过程中存在天然的优势，基于以上目标，
我们大致有一下几点需要注意：
</code></pre><ul>
<li>登录接口不需要保护</li>
<li>登录成功和失败都需要有相应的跳转页面</li>
<li><p>访问受保护资源受限后跳转无权页面</p>
<pre><code>具体底层技术，我们基于springboot2.x+spring security5 +Thymeleaf来实现。
</code></pre><p><strong>1.引入依赖</strong></p>
<pre><code>除了引入springboot应用所需要的基础依赖之外，还要引入security和thymeleaf依赖：
</code></pre><figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">&lt;!-- security --&gt;</div><div class="line">&lt;dependency&gt;</div><div class="line">    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</div><div class="line">    &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;</div><div class="line">&lt;/dependency&gt;</div><div class="line">&lt;!-- thymeleaf --&gt;</div><div class="line">&lt;dependency&gt;</div><div class="line">    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</div><div class="line">    &lt;artifactId&gt;spring-boot-starter-thymeleaf&lt;/artifactId&gt;</div><div class="line">&lt;/dependency&gt;</div></pre></td></tr></table></figure>
</li>
</ul>
<p><strong>2.修改配置文件</strong></p>
<pre><code>修改application.properties主配置文件用以支持Thymeleaf：
</code></pre><figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"># thymeleaf</div><div class="line">spring.thymeleaf.prefix=classpath:/templates/</div><div class="line">spring.thymeleaf.suffix=.html</div><div class="line">spring.thymeleaf.mode=HTML</div><div class="line">spring.thymeleaf.encoding=UTF-8</div><div class="line">spring.thymeleaf.content-type=text/html</div><div class="line"></div><div class="line">spring.thymeleaf.cache=false</div><div class="line">logging.level.org.springframework.security: INFO</div><div class="line">management.endpoints.web.exposure.include=*</div></pre></td></tr></table></figure>
<p><strong>3.编写认证管理类</strong></p>
<pre><code>spring security对于用户的登录认证支持两种模式：
</code></pre><ul>
<li>内存认证：将用户、密码以及对应的权限存放到内存中，暴露InMemoryUserDetailsManager实例注册到spring容器中，来实现用户登录及权限认证</li>
<li><p>数据库认证：大多数商业应用都是采用数据库认证，应用中自己实现UserDetailService或者使用JdbcUserDetailsManager来实现数据库认证。</p>
<pre><code>此处为了方便起见，我们使用内存认证，暴露InMemoryUserDetailsManager实例到容器中：
</code></pre><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Order</span>(Ordered.HIGHEST_PRECEDENCE)</div><div class="line"><span class="meta">@Configuration</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AuthenticationSecurity</span> </span>&#123;</div><div class="line">    <span class="meta">@SuppressWarnings</span>(<span class="string">"deprecation"</span>)</div><div class="line">    <span class="meta">@Bean</span></div><div class="line">    <span class="function"><span class="keyword">public</span> InMemoryUserDetailsManager <span class="title">inMemoryUserDetailsManager</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="keyword">new</span> InMemoryUserDetailsManager(</div><div class="line">                User.withDefaultPasswordEncoder().username(<span class="string">"admin"</span>).password(<span class="string">"admin"</span>)</div><div class="line">                        .roles(<span class="string">"ADMIN"</span>, <span class="string">"USER"</span>, <span class="string">"ACTUATOR"</span>).build(),</div><div class="line">                User.withDefaultPasswordEncoder().username(<span class="string">"user"</span>).password(<span class="string">"user"</span>)</div><div class="line">                        .roles(<span class="string">"USER"</span>).build());</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<pre><code>这段代码的意思是，我们使用InMemoryUserDetailsManager来实现用户权限认证，初始化了两个用户并设置了相应的密码和权限。
</code></pre><p><strong>4.配置权限适配</strong></p>
<pre><code>在控制权限的时候，我们需要对一些接口或者url开白名单，比如登录接口如果加权限的话，就永远登录不了了，还有一些认证成功
</code></pre><p>  或失败后的url跳转，包括静态资源的过滤。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Configuration</span></div><div class="line"><span class="meta">@EnableGlobalMethodSecurity</span>(prePostEnabled =<span class="keyword">true</span>)</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CustomApplicationSecurity</span> <span class="keyword">extends</span> <span class="title">WebSecurityConfigurerAdapter</span> </span>&#123;</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">configure</span><span class="params">(HttpSecurity http)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        <span class="comment">// @formatter:off</span></div><div class="line">        http.authorizeRequests()</div><div class="line">                .antMatchers(<span class="string">"/login"</span>).permitAll()</div><div class="line">                .anyRequest().fullyAuthenticated()</div><div class="line">                .and()</div><div class="line">                .formLogin().loginPage(<span class="string">"/login"</span>).failureUrl(<span class="string">"/login?error"</span>)</div><div class="line">                .and()</div><div class="line">                .logout().logoutRequestMatcher(<span class="keyword">new</span> AntPathRequestMatcher(<span class="string">"/logout"</span>))</div><div class="line">                .and()</div><div class="line">                .exceptionHandling().accessDeniedPage(<span class="string">"/access?error"</span>);</div><div class="line">        <span class="comment">// @formatter:on</span></div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">configure</span><span class="params">(WebSecurity web)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        web.ignoring().antMatchers(<span class="string">"/config/**"</span>, <span class="string">"/css/**"</span>, <span class="string">"/fonts/**"</span>, <span class="string">"/img/**"</span>, <span class="string">"/js/**"</span>);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<pre><code>自定义配置类并继承WebSecurityConfigurerAdapter重写configure方法：
</code></pre></li>
<li>设置登录接口所有人都可以访问</li>
<li>其他接口都需要认证后才能访问</li>
<li>使用表单登录，指定登录url，并且指定登录失败后的跳转</li>
<li>指定登出路径</li>
<li>指定认证失败后的跳转页面</li>
<li>对于静态资源的访问不做权限管控</li>
</ul>
<p><strong>5.开启Security功能</strong></p>
<pre><code>在应用启动类上增加注解@EnableWebSecurity：
</code></pre><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@SpringBootApplication</span></div><div class="line"><span class="meta">@EnableWebSecurity</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">App</span></span></div><div class="line">&#123;</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</div><div class="line">        SpringApplication.run(App.class, args);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><strong>6.编写请求处理器</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Controller</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HomeController</span> </span>&#123;</div><div class="line">    <span class="meta">@GetMapping</span>(<span class="string">"/"</span>)</div><div class="line">    <span class="meta">@PreAuthorize</span>(<span class="string">"hasRole('ADMIN')"</span>)</div><div class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">home</span><span class="params">(Map&lt;String, Object&gt; model)</span> </span>&#123;</div><div class="line">        model.put(<span class="string">"message"</span>, <span class="string">"Hello World"</span>);</div><div class="line">        model.put(<span class="string">"title"</span>, <span class="string">"Hello Home"</span>);</div><div class="line">        model.put(<span class="string">"date"</span>, <span class="keyword">new</span> Date());</div><div class="line">        <span class="keyword">return</span> <span class="string">"home"</span>;</div><div class="line">    &#125;</div><div class="line">    <span class="meta">@GetMapping</span>(<span class="string">"/login"</span>)</div><div class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">index</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="string">"login"</span>;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><strong>7.编写页面文件</strong></p>
<ul>
<li><p>登录主页面</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div></pre></td><td class="code"><pre><div class="line">&lt;!DOCTYPE html&gt;</div><div class="line">&lt;html xmlns:th="http://www.thymeleaf.org"&gt;</div><div class="line">&lt;head&gt;</div><div class="line">    &lt;title&gt;Login&lt;/title&gt;</div><div class="line">    &lt;link rel="stylesheet" th:href="@&#123;/css/bootstrap.min.css&#125;"</div><div class="line">          href="../../css/bootstrap.min.css" /&gt;</div><div class="line">&lt;/head&gt;</div><div class="line">&lt;body onload="document.f.username.focus();"&gt;</div><div class="line">&lt;div class="container"&gt;</div><div class="line">    &lt;div class="navbar"&gt;</div><div class="line">        &lt;div class="navbar-inner"&gt;</div><div class="line">            &lt;a class="brand" href="http://www.thymeleaf.org"&gt; Thymeleaf -</div><div class="line">                Plain &lt;/a&gt;</div><div class="line">            &lt;ul class="nav"&gt;</div><div class="line">                &lt;li&gt;&lt;a th:href="@&#123;/&#125;" href="home.html"&gt; Home &lt;/a&gt;&lt;/li&gt;</div><div class="line">            &lt;/ul&gt;</div><div class="line">        &lt;/div&gt;</div><div class="line">    &lt;/div&gt;</div><div class="line">    &lt;div class="content"&gt;</div><div class="line">        &lt;p th:if="$&#123;param.logout&#125;" class="alert"&gt;You have been logged out&lt;/p&gt;</div><div class="line">        &lt;p th:if="$&#123;param.error&#125;" class="alert alert-error"&gt;There was an error, please try again&lt;/p&gt;</div><div class="line">        &lt;h2&gt;Login with Username and Password&lt;/h2&gt;</div><div class="line">        &lt;form name="form" th:action="@&#123;/login&#125;" action="/login" method="POST"&gt;</div><div class="line">            &lt;fieldset&gt;</div><div class="line">                &lt;input type="text" name="username" value="" placeholder="Username" /&gt;</div><div class="line">                &lt;input type="password" name="password" placeholder="Password" /&gt;</div><div class="line">            &lt;/fieldset&gt;</div><div class="line">            &lt;input type="submit" id="login" value="Login"</div><div class="line">                   class="btn btn-primary" /&gt;</div><div class="line">        &lt;/form&gt;</div><div class="line">    &lt;/div&gt;</div><div class="line">&lt;/div&gt;</div><div class="line">&lt;/body&gt;</div><div class="line">&lt;/html&gt;</div></pre></td></tr></table></figure>
</li>
<li><p>错误页面</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div></pre></td><td class="code"><pre><div class="line">&lt;!DOCTYPE html&gt;</div><div class="line">&lt;html xmlns:th="http://www.thymeleaf.org"&gt;</div><div class="line">&lt;head&gt;</div><div class="line">    &lt;title&gt;Error&lt;/title&gt;</div><div class="line">    &lt;link rel="stylesheet" th:href="@&#123;/css/bootstrap.min.css&#125;"</div><div class="line">          href="../../css/bootstrap.min.css" /&gt;</div><div class="line">&lt;/head&gt;</div><div class="line">&lt;body&gt;</div><div class="line">&lt;div class="container"&gt;</div><div class="line">    &lt;div class="navbar"&gt;</div><div class="line">        &lt;div class="navbar-inner"&gt;</div><div class="line">            &lt;a class="brand" href="http://www.thymeleaf.org"&gt; Thymeleaf -</div><div class="line">                Plain &lt;/a&gt;</div><div class="line">            &lt;ul class="nav"&gt;</div><div class="line">                &lt;li&gt;&lt;a th:href="@&#123;/&#125;" href="home.html"&gt; Home &lt;/a&gt;&lt;/li&gt;</div><div class="line">                &lt;li&gt;&lt;a th:href="@&#123;/logout&#125;" href="logout"&gt; Logout &lt;/a&gt;&lt;/li&gt;</div><div class="line">            &lt;/ul&gt;</div><div class="line">        &lt;/div&gt;</div><div class="line">    &lt;/div&gt;</div><div class="line">    &lt;h1 th:text="$&#123;title&#125;"&gt;Title&lt;/h1&gt;</div><div class="line">    &lt;div id="created" th:text="$&#123;#dates.format(timestamp)&#125;"&gt;July 11,</div><div class="line">        2012 2:17:16 PM CDT&lt;/div&gt;</div><div class="line">    &lt;div&gt;</div><div class="line">        There was an unexpected error (type=&lt;span th:text="$&#123;error&#125;"&gt;Bad&lt;/span&gt;, status=&lt;span th:text="$&#123;status&#125;"&gt;500&lt;/span&gt;).</div><div class="line">    &lt;/div&gt;</div><div class="line">    &lt;div th:text="$&#123;message&#125;"&gt;Fake content&lt;/div&gt;</div><div class="line">    &lt;div&gt;</div><div class="line">        Please contact the operator with the above information.</div><div class="line">    &lt;/div&gt;</div><div class="line">&lt;/div&gt;</div><div class="line">&lt;/body&gt;</div><div class="line">&lt;/html&gt;</div></pre></td></tr></table></figure>
</li>
<li><p>登录成功后主页面</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div></pre></td><td class="code"><pre><div class="line">&lt;!DOCTYPE html&gt;</div><div class="line">&lt;html xmlns:th="http://www.thymeleaf.org"&gt;</div><div class="line">&lt;head&gt;</div><div class="line">    &lt;title th:text="$&#123;title&#125;"&gt;Title&lt;/title&gt;</div><div class="line">    &lt;link rel="stylesheet" th:href="@&#123;/css/bootstrap.min.css&#125;"</div><div class="line">          href="../../css/bootstrap.min.css" /&gt;</div><div class="line">&lt;/head&gt;</div><div class="line">&lt;body&gt;</div><div class="line">&lt;div class="container"&gt;</div><div class="line">    &lt;div class="navbar"&gt;</div><div class="line">        &lt;div class="navbar-inner"&gt;</div><div class="line">            &lt;a class="brand" href="http://www.thymeleaf.org"&gt; Thymeleaf -</div><div class="line">                Plain &lt;/a&gt;</div><div class="line">            &lt;ul class="nav"&gt;</div><div class="line">                &lt;li&gt;&lt;a th:href="@&#123;/&#125;" href="home.html"&gt; Home &lt;/a&gt;&lt;/li&gt;</div><div class="line">                &lt;li&gt;&lt;a th:href="@&#123;/logout&#125;" href="logout"&gt; Logout &lt;/a&gt;&lt;/li&gt;</div><div class="line">            &lt;/ul&gt;</div><div class="line">        &lt;/div&gt;</div><div class="line">    &lt;/div&gt;</div><div class="line">    &lt;h1 th:text="$&#123;title&#125;"&gt;Title&lt;/h1&gt;</div><div class="line">    &lt;div th:text="$&#123;message&#125;"&gt;Fake content&lt;/div&gt;</div><div class="line">    &lt;div id="created" th:text="$&#123;#dates.format(date)&#125;"&gt;July 11,</div><div class="line">        2012 2:17:16 PM CDT&lt;/div&gt;</div><div class="line">&lt;/div&gt;</div><div class="line">&lt;/body&gt;</div><div class="line">&lt;/html&gt;</div></pre></td></tr></table></figure>
</li>
<li><p>访问受限后跳转页面</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div></pre></td><td class="code"><pre><div class="line">&lt;!DOCTYPE html&gt;</div><div class="line">&lt;html xmlns:th="http://www.thymeleaf.org"&gt;</div><div class="line">&lt;head&gt;</div><div class="line">    &lt;title&gt;Error&lt;/title&gt;</div><div class="line">    &lt;link rel="stylesheet" th:href="@&#123;/css/bootstrap.min.css&#125;"</div><div class="line">          href="../../css/bootstrap.min.css" /&gt;</div><div class="line">&lt;/head&gt;</div><div class="line">&lt;body&gt;</div><div class="line">&lt;div class="container"&gt;</div><div class="line">    &lt;div class="navbar"&gt;</div><div class="line">        &lt;div class="navbar-inner"&gt;</div><div class="line">            &lt;a class="brand" href="http://www.thymeleaf.org"&gt; Thymeleaf -</div><div class="line">                Plain &lt;/a&gt;</div><div class="line">            &lt;ul class="nav"&gt;</div><div class="line">                &lt;li&gt;&lt;a th:href="@&#123;/&#125;" href="home.html"&gt; Home &lt;/a&gt;&lt;/li&gt;</div><div class="line">                &lt;li&gt;&lt;a th:href="@&#123;/logout&#125;" href="logout"&gt; Logout &lt;/a&gt;&lt;/li&gt;</div><div class="line">            &lt;/ul&gt;</div><div class="line">        &lt;/div&gt;</div><div class="line">    &lt;/div&gt;</div><div class="line">    &lt;h1 th:text="$&#123;title&#125;"&gt;Title&lt;/h1&gt;</div><div class="line">    &lt;p class="alert alert-error"&gt;Access denied:</div><div class="line">        you do not have permission for that resource&lt;/p&gt;</div><div class="line">    &lt;div th:text="$&#123;message&#125;"&gt;Fake content&lt;/div&gt;</div><div class="line">    &lt;div&gt;Please contact the operator with the above information.&lt;/div&gt;</div><div class="line">&lt;/div&gt;</div><div class="line">&lt;/body&gt;</div><div class="line">&lt;/html&gt;</div></pre></td></tr></table></figure>
</li>
</ul>
<h5 id="测试"><a href="#测试" class="headerlink" title="测试"></a>测试</h5><pre><code>启动应用后，浏览器输入localhost:8080/ ：
</code></pre><img src="/typhoon/2018/11/18/springboot-19-security/sb1.png" alt="springboot" title="springboot">
<pre><code>故意输入一个错误的账号密码：
</code></pre><img src="/typhoon/2018/11/18/springboot-19-security/sb2.png" alt="springboot" title="springboot">
<pre><code>输入普通用户账号和密码：
</code></pre><img src="/typhoon/2018/11/18/springboot-19-security/sb3.png" alt="springboot" title="springboot">
<pre><code>登录成功了，但是跳转的时候接口有做权限管控，需要ADMIN角色：
</code></pre><img src="/typhoon/2018/11/18/springboot-19-security/sb5.png" alt="springboot" title="springboot">
<pre><code>输入admin账号和密码：
</code></pre><img src="/typhoon/2018/11/18/springboot-19-security/sb4.png" alt="springboot" title="springboot">
<pre><code>访问成功。到这里我们也就实现了springboot集成security来实现简单的权限管控。
</code></pre><h5 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h5><pre><code>    目前市面上流行的权限管控框架有很多种，比较常用的就是shiro和security，shiro使用起来更简单，
security与spring应用能够无缝融合，两者孰好孰坏并没有定论，具体使用哪个，完全取决于开发人员的
技术站或者应用的历史原因。
    此篇通过分析和使用代码的方式实现了简单的应用访问权限管控，如果是简单的应用，对于上述的代码
把认证管理工具改成数据库的方式就能直接使用，具体的security实现原理和核心类的架构依赖本篇不做赘述。
希望给大家带来一定的参考价值。
</code></pre>  
	</div>
		<footer class="article-footer clearfix">
<div class="article-catetags">

<div class="article-categories">
  <span></span>
  <a class="article-category-link" href="/typhoon/categories/springboot/">springboot</a>
</div>


  <div class="article-tags">
  
  <span></span> <a href="/typhoon/tags/springboot/">springboot</a>
  </div>

</div>



	<div class="article-share" id="share">
	
	  <div data-url="http://scorpioaeolus.oschina.io/2018/11/18/springboot-19-security/" data-title="springboot(19)-security | Typhoon&#39;s code space" data-tsina="null" class="share clearfix">
	  </div>
	
	</div>


</footer>

   	       
	</article>
	
<nav class="article-nav clearfix">
 
 <div class="prev" >
 <a href="/typhoon/2018/11/24/springboot应用关闭方式/" title="springboot应用关闭方式">
  <strong>上一篇：</strong><br/>
  <span>
  springboot应用关闭方式</span>
</a>
</div>


<div class="next">
<a href="/typhoon/2018/11/17/高并发场景缓存真的可靠吗？/"  title="高并发场景缓存真的可靠吗？">
 <strong>下一篇：</strong><br/> 
 <span>高并发场景缓存真的可靠吗？
</span>
</a>
</div>

</nav>

	


</div>  
      <div class="openaside"><a class="navbutton" href="#" title="Show Sidebar"></a></div>

  <div id="toc" class="toc-aside">
  <strong class="toc-title">Contents</strong>
 
 <ol class="toc"><li class="toc-item toc-level-5"><a class="toc-link" href="#目标"><span class="toc-number">1.</span> <span class="toc-text">目标</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#技术实现"><span class="toc-number">2.</span> <span class="toc-text">技术实现</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#测试"><span class="toc-number">3.</span> <span class="toc-text">测试</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#总结"><span class="toc-number">4.</span> <span class="toc-text">总结</span></a></li></ol>
 
  </div>

<div id="asidepart">
<div class="closeaside"><a class="closebutton" href="#" title="Hide Sidebar"></a></div>
<aside class="clearfix">

  


  
<div class="categorieslist">
	<p class="asidetitle">Categories</p>
		<ul>
		
		  
			<li><a href="/typhoon/categories/dubbo/" title="dubbo">dubbo<sup>8</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/java性能优化/" title="java性能优化">java性能优化<sup>17</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/java源码分析/" title="java源码分析">java源码分析<sup>1</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/motan/" title="motan">motan<sup>2</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/spring/" title="spring">spring<sup>11</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/springboot/" title="springboot">springboot<sup>28</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/springmvc/" title="springmvc">springmvc<sup>1</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/容器/" title="容器">容器<sup>1</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/工具/" title="工具">工具<sup>7</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/性能优化/" title="性能优化">性能优化<sup>5</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/架构/" title="架构">架构<sup>8</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/案例分析/" title="案例分析">案例分析<sup>13</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/缓存/" title="缓存">缓存<sup>4</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/设计模式/" title="设计模式">设计模式<sup>3</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/面试题/" title="面试题">面试题<sup>1</sup></a></li>
		  
		
		</ul>
</div>


  
<div class="tagslist">
	<p class="asidetitle">Tags</p>
		<ul class="clearfix">
		
			
				<li><a href="/typhoon/tags/springboot/" title="springboot">springboot<sup>28</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/java性能优化/" title="java性能优化">java性能优化<sup>9</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/限流/" title="限流">限流<sup>3</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/Spring5/" title="Spring5">Spring5<sup>3</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/设计模式/" title="设计模式">设计模式<sup>3</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/案例分析/" title="案例分析">案例分析<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/性能优化/" title="性能优化">性能优化<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/Spring/" title="Spring">Spring<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/dubbo/" title="dubbo">dubbo<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/分页/" title="分页">分页<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/并发/" title="并发">并发<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/异常拦截/" title="异常拦截">异常拦截<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/dubbo分布式事务/" title="dubbo分布式事务">dubbo分布式事务<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/自带图片/" title="自带图片">自带图片<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/svn导出mvn项目/" title="svn导出mvn项目">svn导出mvn项目<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/dubbo过滤器/" title="dubbo过滤器">dubbo过滤器<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/排序性能对比/" title="排序性能对比">排序性能对比<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/ListenableFuture/" title="ListenableFuture">ListenableFuture<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/PropertyChangeListener/" title="PropertyChangeListener">PropertyChangeListener<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/jdbcTemplate高可用/" title="jdbcTemplate高可用">jdbcTemplate高可用<sup>1</sup></a></li>
			
		
		</ul>
</div>


  <div class="linkslist">
  <p class="asidetitle">Links</p>
    <ul>
        
          <li>
            
            	<a href="https://coderq.com" target="_blank" title="一个面向程序员交流分享的新一代社区">码农圈</a>
            
          </li>
        
          <li>
            
            	<a href="http://wuchong.me" target="_blank" title="Jark&#39;s Blog">Jark&#39;s Blog</a>
            
          </li>
        
    </ul>
</div>

  


  <div class="rsspart">
	<a href="/atom.xml" target="_blank" title="rss">RSS</a>
</div>

  <div class="weiboshow">
  <p class="asidetitle">Weibo</p>
    <iframe width="100%" height="119" class="share_self"  frameborder="0" scrolling="no" src="http://widget.weibo.com/weiboshow/index.php?language=&width=0&height=119&fansRow=2&ptype=1&speed=0&skin=9&isTitle=1&noborder=1&isWeibo=0&isFans=0&uid=null&verifier=b3593ceb&dpc=1"></iframe>
</div>


</aside>
</div>
    </div>
    <footer><div id="footer" >
	
	<div class="line">
		<span></span>
		<div class="author"></div>
	</div>
	
	
	<section class="info">
		<p> Hello ,I&#39;m a java coder. <br/>
			This is my blog,believe it or not.</p>
	</section>
	 
	<div class="social-font" class="clearfix">
		
		
		
		
		
		
		
		
		
		
		<a href="mailto:ScorpioAeolus@163.com" target="_blank" class="icon-email" title="Email Me"></a>
		
	</div>
			
		

		<p class="copyright">
		Powered by <a href="http://hexo.io" target="_blank" title="hexo">hexo</a> and Theme by <a href="https://github.com/wuchong/jacman" target="_blank" title="Jacman">Jacman</a> © 2019 
		
		<a href="/typhoon/about" target="_blank" title="typhoon">typhoon</a>
		
		
		</p>
</div>
</footer>
    <script src="/typhoon/js/jquery-2.0.3.min.js"></script>
<script src="/typhoon/js/jquery.imagesloaded.min.js"></script>
<script src="/typhoon/js/gallery.js"></script>
<script src="/typhoon/js/jquery.qrcode-0.12.0.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){ 
  $('.navbar').click(function(){
    $('header nav').toggleClass('shownav');
  });
  var myWidth = 0;
  function getSize(){
    if( typeof( window.innerWidth ) == 'number' ) {
      myWidth = window.innerWidth;
    } else if( document.documentElement && document.documentElement.clientWidth) {
      myWidth = document.documentElement.clientWidth;
    };
  };
  var m = $('#main'),
      a = $('#asidepart'),
      c = $('.closeaside'),
      o = $('.openaside');
  c.click(function(){
    a.addClass('fadeOut').css('display', 'none');
    o.css('display', 'block').addClass('fadeIn');
    m.addClass('moveMain');
  });
  o.click(function(){
    o.css('display', 'none').removeClass('beforeFadeIn');
    a.css('display', 'block').removeClass('fadeOut').addClass('fadeIn');      
    m.removeClass('moveMain');
  });
  $(window).scroll(function(){
    o.css("top",Math.max(80,260-$(this).scrollTop()));
  });
  
  $(window).resize(function(){
    getSize(); 
    if (myWidth >= 1024) {
      $('header nav').removeClass('shownav');
    }else{
      m.removeClass('moveMain');
      a.css('display', 'block').removeClass('fadeOut');
      o.css('display', 'none');
      
      $('#toc.toc-aside').css('display', 'none');
        
    }
  });
});
</script>

<script type="text/javascript">
$(document).ready(function(){ 
  var ai = $('.article-content>iframe'),
      ae = $('.article-content>embed'),
      t  = $('#toc'),
      ta = $('#toc.toc-aside'),
      o  = $('.openaside'),
      c  = $('.closeaside');
  if(ai.length>0){
    ai.wrap('<div class="video-container" />');
  };
  if(ae.length>0){
   ae.wrap('<div class="video-container" />');
  };
  c.click(function(){
    ta.css('display', 'block').addClass('fadeIn');
  });
  o.click(function(){
    ta.css('display', 'none');
  });
  $(window).scroll(function(){
    ta.css("top",Math.max(140,320-$(this).scrollTop()));
  });
});
</script>


<script type="text/javascript">
$(document).ready(function(){ 
  var $this = $('.share'),
      url = $this.attr('data-url'),
      encodedUrl = encodeURIComponent(url),
      title = $this.attr('data-title'),
      tsina = $this.attr('data-tsina'),
      description = $this.attr('description');
  var html = [
  '<div class="hoverqrcode clearfix"></div>',
  '<a class="overlay" id="qrcode"></a>',
  '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="article-share-facebook" target="_blank" title="Facebook"></a>',
  '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="article-share-twitter" target="_blank" title="Twitter"></a>',
  '<a href="#qrcode" class="article-share-qrcode" title="微信"></a>',
  '<a href="http://widget.renren.com/dialog/share?resourceUrl=' + encodedUrl + '&srcUrl=' + encodedUrl + '&title=' + title +'" class="article-share-renren" target="_blank" title="人人"></a>',
  '<a href="http://service.weibo.com/share/share.php?title='+title+'&url='+encodedUrl +'&ralateUid='+ tsina +'&searchPic=true&style=number' +'" class="article-share-weibo" target="_blank" title="微博"></a>',
  '<span title="Share to"></span>'
  ].join('');
  $this.append(html);

  $('.hoverqrcode').hide();

  var myWidth = 0;
  function updatehoverqrcode(){
    if( typeof( window.innerWidth ) == 'number' ) {
      myWidth = window.innerWidth;
    } else if( document.documentElement && document.documentElement.clientWidth) {
      myWidth = document.documentElement.clientWidth;
    };
    var qrsize = myWidth > 1024 ? 200:100;
    var options = {render: 'image', size: qrsize, fill: '#2ca6cb', text: url, radius: 0.5, quiet: 1};
    var p = $('.article-share-qrcode').position();
    $('.hoverqrcode').empty().css('width', qrsize).css('height', qrsize)
                          .css('left', p.left-qrsize/2+20).css('top', p.top-qrsize-10)
                          .qrcode(options);
  };
  $(window).resize(function(){
    $('.hoverqrcode').hide();
  });
  $('.article-share-qrcode').click(function(){
    updatehoverqrcode();
    $('.hoverqrcode').toggle();
  });
  $('.article-share-qrcode').hover(function(){}, function(){
      $('.hoverqrcode').hide();
  });
});   
</script>









<link rel="stylesheet" href="/typhoon/fancybox/jquery.fancybox.css" media="screen" type="text/css">
<script src="/typhoon/fancybox/jquery.fancybox.pack.js"></script>
<script type="text/javascript">
$(document).ready(function(){ 
  $('.article-content').each(function(i){
    $(this).find('img').each(function(){
      if ($(this).parent().hasClass('fancybox')) return;
      var alt = this.alt;
      if (alt) $(this).after('<span class="caption">' + alt + '</span>');
      $(this).wrap('<a href="' + this.src + '" title="' + alt + '" class="fancybox"></a>');
    });
    $(this).find('.fancybox').each(function(){
      $(this).attr('rel', 'article' + i);
    });
  });
  if($.fancybox){
    $('.fancybox').fancybox();
  }
}); 
</script>



<!-- Analytics Begin -->



<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "//hm.baidu.com/hm.js?e6d1f421bbc9962127a50488f9ed37d1";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>



<!-- Analytics End -->

<!-- Totop Begin -->

	<div id="totop">
	<a title="Back to Top"><img src="/typhoon/img/scrollup.png"/></a>
	</div>
	<script src="/typhoon/js/totop.js"></script>

<!-- Totop End -->

<!-- MathJax Begin -->
<!-- mathjax config similar to math.stackexchange -->


<!-- MathJax End -->

<!-- Tiny_search Begin -->

<!-- Tiny_search End -->

  </body>
</html>
